package love.server.handler;

import java.util.List;

import love.model.Joueur;
import love.server.JSONTCPServer;
import love.sock.model.BadRequestException;
import love.sock.model.EStatus;
import love.sock.model.Request;
import love.utils.NumericTools;

import com.thetransactioncompany.jsonrpc2.JSONRPC2Error;
import com.thetransactioncompany.jsonrpc2.JSONRPC2Request;
import com.thetransactioncompany.jsonrpc2.JSONRPC2Response;
import com.thetransactioncompany.jsonrpc2.server.MessageContext;

public class PlayerStateHandler extends AbstractLoveHandler {
	
	public PlayerStateHandler(JSONTCPServer server) {
		super(server);
	}
	
	// Reports the method names of the handled requests
	public String[] handledRequests() {
		return new String[]{"player_state"};
	}
	
	@Override
	public String getMethod() {
		return JSONTCPServer.METHOD_GET;
	}

	@Override
	public JSONRPC2Response process(Request request, MessageContext requestCtx) throws BadRequestException {
		if (request.getAction().equals("player_state")) {
			List<String> params = request.getParams();
			if(params.size() < 2){
				throw new BadRequestException(EStatus.ERROR400, "<id_joueur> GET player_state <id_game>, <num_player>");
			}
			Joueur joueur = server.getPlayerByNum(NumericTools.parseInteger(params.get(1)));
			if(joueur == null){
				throw new BadRequestException(EStatus.ERROR400, "Player "+params.get(1)+" not found");
			}
			
			JSONRPC2Response response = server.buildBasicResponse(request, "", EStatus.MESSAGE200, null);
			response.setResult(joueur.getPlayerDescription(request.getID().equals(joueur.getId())));
			
			return response;
		}
		else {
			// Method name not supported
			return new JSONRPC2Response(JSONRPC2Error.METHOD_NOT_FOUND, request.getID());
		}
	}

	@Override
	public JSONRPC2Response process(JSONRPC2Request request,
			MessageContext requestCtx) {
		return null;
	}
}
